﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using vuonthieunhi.Models;
using vuonthieunhi.Library;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Net.Mail;
using Pagination;
using System.Collections;
using Excel = Microsoft.Office.Interop.Excel;
namespace vuonthieunhi.Controllers
{
    [HandleError]
    public class HomeController : BaseController
    {
        PartnerDao partDao = new PartnerDao();
        PaymentDao paymentDao = new PaymentDao();
        CategoryDao catDao = new CategoryDao();
        int defaultPageSize = 30;


        public ActionResult Index(string alias)
        {
            ViewData["CategoryMenu"] = catDao.GetCategoryByParentID(0);
            ViewData["ListNewPartner"] = partDao.GetNewPartner();
           // 
            //ReadInterviewDataFromExcel();
            return View();
        }
        public void set()
        {
            partDao.listPromotion(2, 10);
        }
        public void ReadInterviewDataFromExcel()
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(Server.MapPath(Constants.UPLOAD_ADV_ + "hung.xlsx"));
            Excel.Worksheet xlWorkSheet = xlWorkBook.Worksheets.get_Item(1);
            List<Partner> list = new List<Partner>();
            try
            {
                for (int i = 1; i <= 54; i++)
                {
                    Partner partner = partDao.GetByID(int.Parse(xlWorkSheet.get_Range("A" + i).Text));
                    partner.CurrentPrice = double.Parse(xlWorkSheet.get_Range("C" + i).Text);
                    partner.OldPrice = null;
                    partDao.Update(partner);
                }
            }
            finally
            {
                xlWorkBook.Close();
                xlApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                xlWorkSheet = null;
                xlWorkBook = null;
                xlApp = null;
            }
            //return list;
        }

        private void SetPartnerName()
        {
            List<sp_GetPartnerResult> list = partDao.GetPartner("", 0);
            foreach (sp_GetPartnerResult item in list)
            {
                Partner obj = partDao.GetByID(item.ID);
                obj.Alias = FRouter.ConvertTextToNoMark(item.PartnerName);
                obj.SubName = obj.Alias.Replace("-", " ");
                partDao.Update(obj);
            }
        }

        [HttpPost]
        public ActionResult GlobalSearch(FormCollection request, int? trang)
        {
            string globalKeyWord = string.Empty;
            if (trang.HasValue)
            {
                globalKeyWord = Session["GlobalKeyWord"] != null ? (string)Session["GlobalKeyWord"] : string.Empty;
                List<sp_GetPartnerResult> listGlobalSearch = partDao.GetPartner(globalKeyWord, 0);
                int currentPageIndex = trang.HasValue ? trang.Value : 1;
                var list = listGlobalSearch.ToPagedList(currentPageIndex, defaultPageSize);
                return PartialView("GlobalSearchList", list);
            }
            else
            {
                globalKeyWord = request["btnSearch"];
                List<sp_GetPartnerResult> listGlobalSearch = partDao.GetPartner(globalKeyWord, 0);
                Session["GlobalKeyWord"] = globalKeyWord;
                //ViewData["SeachListPartner"] = partDao.GetPartner(globalKeyWord, 0);
                ViewData["CategoryMenu"] = catDao.GetCategoryByParentID(0);
                int currentPageIndex = trang.HasValue ? trang.Value : 1;
                var list = listGlobalSearch.ToPagedList(currentPageIndex, defaultPageSize);
                return View(list);
            }

        }

        [HttpPost]
        public ActionResult AdvanceSearch(FormCollection request, int? trang)
        {
            if (Request.IsAjaxRequest())
            {
                Hashtable hash = (Hashtable)Session["SetAdvanSearch"];
                string name = (string)hash["Name"];
                int category = Constants.ConvertToInt(hash["CategoryID"]);
                double fromMoney = Constants.ConvertToDouble(hash["FromMoney"]);
                double toMoney = Constants.ConvertToDouble(hash["ToMoney"]);
                int manufacturer = Constants.ConvertToInt(hash["ManufacturerID"]);
                List<sp_GetGlobalSearchResult> listAdvanSearch = partDao.GetAdvanceSearch(name, category, manufacturer, fromMoney, toMoney);
                int currentPageIndex = trang.HasValue ? trang.Value : 1;
                var list = listAdvanSearch.ToPagedList(currentPageIndex, defaultPageSize);
                return PartialView("AdvanceSearchList", list);
            }
            else
            {
                string name = request["Name"];
                int category = Constants.ConvertToInt(request["CategoryID"]);
                int manufacturer = Constants.ConvertToInt(request["ManufacturerID"]);
                double fromMoney = Constants.ConvertToDouble(request["FromMoney"]);
                double toMoney = Constants.ConvertToDouble(request["ToMoney"]);
                Hashtable hash = new Hashtable();
                hash.Add("Name", name);
                hash.Add("CategoryID", category);
                hash.Add("ManufacturerID", manufacturer);
                hash.Add("FromMoney", fromMoney);
                hash.Add("ToMoney", toMoney);
                Session["SetAdvanSearch"] = hash;
                return RedirectToAction("AdvanceSearch");
            }

        }


        public ActionResult AdvanceSearch(int? trang)
        {
            List<GetCategoryResult> listCategory = catDao.GetCategoryByParentID(0);
            List<sp_GetGlobalSearchResult> listAdvanSearch = new List<sp_GetGlobalSearchResult>();
            if (Session["SetAdvanSearch"] == null)
            {
                ViewData["CategoryMenu"] = listCategory;
                ViewData["CategoryID"] = new SelectList(listCategory, "ID", "CategoryName", "");
                ViewData["ManufacturerID"] = new SelectList(new ManufacturerDao().GetList(), "ID", "Name", "");
                return View();
            }
            else
            {
                Hashtable hash = (Hashtable)Session["SetAdvanSearch"];
                string name = (string)hash["Name"];
                ViewData["Name"] = name;
                int category = Constants.ConvertToInt(hash["CategoryID"]);
                ViewData["CategoryID"] = category;
                double fromMoney = Constants.ConvertToDouble(hash["FromMoney"]);
                ViewData["FromMoney"] = fromMoney;
                double toMoney = Constants.ConvertToDouble(hash["ToMoney"]);
                ViewData["ToMoney"] = toMoney;
                ViewData["CategoryMenu"] = listCategory;
                int manufacturer = Constants.ConvertToInt(hash["ManufacturerID"]);
                ViewData["CategoryID"] = new SelectList(listCategory, "ID", "CategoryName", category);
                ViewData["ManufacturerID"] = new SelectList(new ManufacturerDao().GetList(), "ID", "Name", manufacturer);
                listAdvanSearch = partDao.GetAdvanceSearch(name, category, manufacturer, fromMoney, toMoney);
                int currentPageIndex = trang.HasValue ? trang.Value : 1;
                var list = listAdvanSearch.ToPagedList(currentPageIndex, defaultPageSize);
                if (Request.IsAjaxRequest())
                    return PartialView("AdvanceSearchList", list);
                else
                    return View(list);
            }
        }

        public ActionResult Product(string alias)
        {
            Category objCategory = catDao.GetByAlias(alias);

            if (objCategory != null)
            {
                if (alias == "do-dung-cho-be" || alias == "do-choi-tre-em")
                {
                    ViewData["HasSubCaterogry"] = true;
                }
                if (objCategory.ParentId.HasValue)
                {
                    ViewData["CategoryMenu"] = catDao.GetCategoryByParentID(objCategory.ParentId.Value).Where(q => q.ParentID.HasValue).ToList();
                    switch (objCategory.Category1.Alias)
                    {
                        case "do-dung-cho-be":
                            ViewData["TitleHeader"] = "<h1 class='child'>" + objCategory.CategoryName + "</h1>";
                            ViewData["ClassName"] = "class='pro child'";
                            ViewData["CssClass"] = "pricebg_newrelease";
                            break;
                        case "do-dung-cho-me":
                            ViewData["TitleHeader"] = "<h1 class='about'>" + objCategory.CategoryName + "</h1>";
                            ViewData["ClassName"] = "class='pro'";
                            ViewData["CssClass"] = "pricebg_clearance";
                            break;
                        case "do-choi-tre-em":
                            ViewData["TitleHeader"] = "<h1 class='titlebar'>" + objCategory.CategoryName + "</h1>";
                            ViewData["ClassName"] = "class='pro toy'";
                            ViewData["CssClass"] = "pricebg_generic";
                            break;
                        case "tui-xach":
                            ViewData["TitleHeader"] = "<h1 class='bag'>" + objCategory.CategoryName + "</h1>";
                            ViewData["CssClass"] = "pricebg_feeding";
                            break;
                        case "sua":
                            ViewData["TitleHeader"] = "<h1 class='events'>" + objCategory.CategoryName + "</h1>";
                            ViewData["CssClass"] = "pricebg_outabout";
                            break;
                        case "cac-loai-khac":
                            ViewData["TitleHeader"] = "<h1 class='contact'>" + objCategory.CategoryName + "</h1>";
                            ViewData["CssClass"] = "pricebg_health";
                            break;
                    }
                    ViewData["BreadCumb"] = "<a href='/danh-muc/" + objCategory.Category1.Alias + ".html'>" + objCategory.Category1.CategoryName + "</a>"
                        + "&nbsp;&nbsp;<img src='../../Themes/images/breadcrumb_separator.gif' />&nbsp;"
                        +"<a href='" + Request.Url.AbsolutePath + "'>" + objCategory.CategoryName + "</a>";
                }
                else
                {
                    List<GetCategoryResult> listCategory = catDao.GetCategoryByParentID(objCategory.ID).ToList();
                    if (alias == "do-dung-cho-be" || alias == "do-choi-tre-em")
                    {
                        listCategory = listCategory.Where(q => q.ParentID.HasValue).ToList();
                    }
                    ViewData["CategoryMenu"] = listCategory;
                    switch (alias)
                    {
                        case "do-dung-cho-be":
                            ViewData["TitleHeader"] = "<h1 class='child'>" + objCategory.CategoryName + "</h1>";
                            ViewData["ClassName"] = "class='pro child'";
                            ViewData["CssClass"] = "pricebg_newrelease";
                            break;
                        case "do-dung-cho-me":
                            ViewData["TitleHeader"] = "<h1 class='about'>" + objCategory.CategoryName + "</h1>";
                            ViewData["ClassName"] = "class='pro'";
                            ViewData["CssClass"] = "pricebg_clearance";
                            break;
                        case "do-choi-tre-em":
                            ViewData["TitleHeader"] = "<h1 class='titlebar'>" + objCategory.CategoryName + "</h1>";
                            ViewData["ClassName"] = "class='pro toy'";
                            ViewData["CssClass"] = "pricebg_generic";
                            break;
                        case "tui-xach":
                            ViewData["TitleHeader"] = "<h1 class='bag'>" + objCategory.CategoryName + "</h1>";
                            ViewData["CssClass"] = "pricebg_feeding";
                            break;
                        case "sua":
                            ViewData["TitleHeader"] = "<h1 class='events'>" + objCategory.CategoryName + "</h1>";
                            ViewData["CssClass"] = "pricebg_outabout";
                            break;
                        case "cac-loai-khac":
                            ViewData["TitleHeader"] = "<h1 class='contact'>" + objCategory.CategoryName + "</h1>";
                            ViewData["CssClass"] = "pricebg_health";
                            break;
                    }
                    ViewData["BreadCumb"] = "<a href='" + Request.Url.AbsolutePath + "'>" + objCategory.CategoryName + "</a>";
                }
                ViewData["ListProduct"] = partDao.GetPartner("", objCategory.ID);
                ViewData["CategoryName"] = objCategory.CategoryName;
            }

            return View();
        }

        public ActionResult Articles(string alias)
        {
            ViewData["CategoryMenu"] = catDao.GetCategoryByParentID(0);
            Article obj = new ArticlesDao().GetArticleByAllias(alias);
            if (obj != null)
            {
                switch (alias)
                {
                    case "che-do-bao-hanh":
                        ViewData["TitleContent"] = "<h1 class='contact'>" + obj.Title + "</h1>";
                        break;
                    case "huong-dan":
                        ViewData["TitleContent"] = "<h1 class='bag'>" + obj.Title + "</h1>";
                        break;
                    case "lien-he":
                        ViewData["TitleContent"] = "<h1 class='child'>" + obj.Title + "</h1>";
                        break;
                }

                return View(obj);
            }
            else
                return RedirectToAction("Index");
        }

        public ActionResult ProductView(string alias)
        {
            ViewData["CategoryMenu"] = catDao.GetCategoryByParentID(0);
            switch (alias)
            {
                case "hang-ban-chay":
                    List<GetHotPartnerResult> listHotPartner = partDao.GetHotPartner();
                    ViewData["ListHotPartner"] = listHotPartner;
                    return View("HotPartner");
                case "hang-khuyen-mai":
                    List<GetSalesPartnerResult> listSalesPartner = partDao.GetSalesPartner();
                    ViewData["ListSalesPartner"] = listSalesPartner;
                    return View("SalesPartner");
            }
            return View();
        }

        public ActionResult Detail(string alias)
        {
            Partner obj = partDao.GetByAlias(alias);
            if (obj == null)
            {
                return View("Error");
            }
            obj.Views += 1;
            partDao.UpdateView(obj);
            Category objCategory = catDao.GetByAlias(obj.Category.Alias);
            if (objCategory.ParentId.HasValue)
            {
                ViewData["BreadCumb"] = "<a href='/danh-muc/" + objCategory.Category1.Alias + ".html'>" + objCategory.Category1.CategoryName + "</a>"
                        + "&nbsp;&nbsp;<img src='../../Themes/images/breadcrumb_separator.gif' />&nbsp;"
                        + "<a href='/danh-muc/" + objCategory.Alias + ".html'>" + objCategory.CategoryName + "</a>"
                        + "&nbsp;&nbsp;<img src='../../Themes/images/breadcrumb_separator.gif' />&nbsp;"
                        + "<a href='" + Request.Url.AbsolutePath + "'>" + obj.PartnerName + "</a>";
                switch (objCategory.Category1.Alias)
                {
                    case "do-dung-cho-be":
                        ViewData["TitleHeader"] = "<h1 class='child'>" + obj.PartnerName + "</h1>";
                        break;
                    case "do-dung-cho-me":
                        ViewData["TitleHeader"] = "<h1 class='about'>" + obj.PartnerName + "</h1>";
                        break;
                    case "do-choi-tre-em":
                        ViewData["TitleHeader"] = "<h1 class='titlebar'>" + obj.PartnerName + "</h1>";
                        break;
                    case "tui-xach":
                        ViewData["TitleHeader"] = "<h1 class='bag'>" + obj.PartnerName + "</h1>";
                        break;
                    case "sua":
                        ViewData["TitleHeader"] = "<h1 class='events'>" + obj.PartnerName + "</h1>";
                        break;
                    case "cac-loai-khac":
                        ViewData["TitleHeader"] = "<h1 class='contact'>" + obj.PartnerName + "</h1>";
                        break;
                }
            }
            else
            {
                ViewData["BreadCumb"] ="<a href='/danh-muc/" + objCategory.Alias + ".html'>" + objCategory.CategoryName + "</a>"
                        + "&nbsp;&nbsp;<img src='../../Themes/images/breadcrumb_separator.gif' />&nbsp;"
                        + "<a href='" + Request.Url.AbsolutePath + "'>" + obj.PartnerName + "</a>";
                switch (objCategory.Alias)
                {
                    case "do-dung-cho-be":
                        ViewData["TitleHeader"] = "<h1 class='child'>" + obj.PartnerName + "</h1>";
                        break;
                    case "do-dung-cho-me":
                        ViewData["TitleHeader"] = "<h1 class='about'>" + obj.PartnerName + "</h1>";
                        break;
                    case "do-choi-tre-em":
                        ViewData["TitleHeader"] = "<h1 class='titlebar'>" + obj.PartnerName + "</h1>";
                        break;
                    case "tui-xach":
                        ViewData["TitleHeader"] = "<h1 class='bag'>" + obj.PartnerName + "</h1>";
                        break;
                    case "sua":
                        ViewData["TitleHeader"] = "<h1 class='events'>" + obj.PartnerName + "</h1>";
                        break;
                    case "cac-loai-khac":
                        ViewData["TitleHeader"] = "<h1 class='contact'>" + obj.PartnerName + "</h1>";
                        break;
                }
            }
            ViewData["CategoryMenu"] = new CategoryDao().GetCategoryByParentID(0);
            return View(obj);
        }

        public ActionResult Payment()
        {
            ViewData["CategoryMenu"] = new CategoryDao().GetCategoryByParentID(0);
            ViewData["ListOrders"] = GetOrderList();
            return View();
        }

        public ActionResult Order()
        {
            ViewData["CategoryMenu"] = new CategoryDao().GetCategoryByParentID(0);
            ViewData["ListOrders"] = GetOrderList();
            return View();
        }

        public ActionResult Info()
        {
            ViewData["CategoryMenu"] = new CategoryDao().GetCategoryByParentID(0);
            ViewData["ListOrders"] = GetOrderList();
            return View();
        }

        public ActionResult ErrorOrder()
        {
            ViewData["CategoryMenu"] = new CategoryDao().GetCategoryByParentID(0);
            ViewData["ListOrders"] = GetOrderList();
            return View();
        }

        [HttpPost]
        public ActionResult Order(FormCollection collection)
        {
            try
            {
                Payment payment = new Payment();
                payment.Name = collection["Name"];
                payment.Address = collection["Address"];
                payment.Phone = collection["Phone"];
                payment.Email = collection["Email"];
                payment.Note = collection["Note"];
                payment.CreateDate = DateTime.Now;

                //Check capcha here
                if (collection["txtCapcha"] == (string)TempData["CaptchaValue"])
                {
                    List<Order> list = GetOrderList();
                    paymentDao.Insert(payment, list);
                    //Clear Cookie
                    HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
                    orderCookie.Value = string.Empty;
                    orderCookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(orderCookie);
                    if (!string.IsNullOrEmpty(payment.Email))
                    {
                        string from_email = ConfigurationManager.AppSettings["from_email"];
                        string host = ConfigurationManager.AppSettings["mailserver_host"];
                        string port = ConfigurationManager.AppSettings["mailserver_port"];
                        string poster = "Vuonthieunhi.com";
                        string subject = "Thông tin từ Vuonthieunhi.com";
                        string body = "Chào bạn <b>" + payment.Name + "</b>,<br/><br/>";
                        body += "Bạn đã đặt hàng thành công trên website vuonthieunhi.com .<br/><br/>";
                        body += "Hàng bạn đã đặt gồm có:<br/><br/>";
                        double dtotal = 0;
                        string strtotal = string.Empty;
                        foreach (Order item in list)
                        {
                            body += "-" + item.Quantity + " " + item.ProductName + ", giá:" + (item.SubTotal == 0 ? "Call" : String.Format("{0:0,0} đ", item.SubTotal)) + "<br/><br/>";
                            dtotal += item.SubTotal;
                            if (item.SubTotal == 0 && strtotal != "Call")
                            {
                                strtotal = "Call";
                            }
                        }

                        if (strtotal != "Call")
                        {
                            strtotal = String.Format("{0:0,0} đ", dtotal);
                        }
                        body += "<b>Tổng tiền: " + strtotal + "</b><br/><br/>";
                        body += "Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất.<br/><br/>";
                        body += "Cảm ơn bạn đã quan tâm tới dịch vụ của chúng tôi";
                        SendMail(host, port, from_email, poster, payment.Email, "", subject, body);
                    }
                    TempData["MessageSuccess"] = "Bạn đã đặt hàng thành công trên website vuonthieunhi.com !";
                    return Redirect("/thong-bao.html");
                }
                else
                {

                    ViewData["CategoryMenu"] = new CategoryDao().GetCategoryByParentID(0);
                    ViewData["ListOrders"] = GetOrderList();
                    ViewData["OrderName"] = collection["Name"];
                    ViewData["OrderAddress"] = collection["Address"];
                    ViewData["OrderPhone"] = collection["Phone"];
                    ViewData["OrderEmail"] = collection["Email"];
                    ViewData["OrderNote"] = collection["Note"];
                    ViewData["CapchaNote"] = "Mã bảo vệ bị sai.Xin vui lòng nhập lại";
                    return View();
                }
            }
            catch
            {
                ViewData["CategoryMenu"] = new CategoryDao().GetCategoryByParentID(0);
                ViewData["ListOrders"] = GetOrderList();
                ViewData["OrderName"] = collection["Name"];
                ViewData["OrderAddress"] = collection["Address"];
                ViewData["OrderPhone"] = collection["Phone"];
                ViewData["OrderEmail"] = collection["Email"];
                ViewData["OrderNote"] = collection["Note"];
                return Redirect("/trang-loi.html");
            }
        }

        #region Shopping Cart

        [HttpPost]
        public ActionResult UpdateCart(FormCollection request)
        {
            int index = 0;
            List<Order> list = GetOrderList();
            while (!string.IsNullOrEmpty(request["hidID" + index]))
            {
                int partnerID = Constants.ConvertToInt(request["hidID" + index]);
                Order existOrder = list.Where(c => c.Id == partnerID).FirstOrDefault<Order>();
                if (existOrder != null)
                {
                    Order order = new Order();
                    order.Id = existOrder.Id;
                    order.ProductName = existOrder.ProductName;
                    order.Quantity = Constants.ConvertToInt(request["hidQuantity" + index]);
                    order.Price = existOrder.Price;
                    order.SubTotal = order.Quantity * existOrder.Price;
                    order.Alias = existOrder.Alias;
                    list.Add(order);
                    list.Remove(existOrder);
                }
                index++;
            }
            AddToCookie(list);
            return RedirectToAction("Payment");
        }

        public JsonResult AddToCart(string productID, string quality)
        {
            JsonResult result = new JsonResult();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
            if (orderCookie == null)
            {
                orderCookie = new HttpCookie(Constants.ORDER_COOKIE);
            }
            int tempQuality = 0;
            int tempID = 0;
            tempQuality = Constants.ConvertToInt(quality);
            tempID = Constants.ConvertToInt(productID);
            Partner obj = partDao.GetByID(tempID);
            if (obj != null && tempQuality > 0)
            {
                List<Order> list = GetOrderList();
                Order existOrder = list.Where(c => c.Id == obj.ID).FirstOrDefault<Order>();

                Order order = new Order();
                if (existOrder != null)
                {
                    order.Id = obj.ID;
                    order.ProductName = obj.PartnerName;
                    order.Price = obj.CurrentPrice.Value;
                    order.Quantity = tempQuality + existOrder.Quantity;
                    order.SubTotal = order.Quantity * obj.CurrentPrice.Value;
                    order.Alias = existOrder.Alias;
                    list.Add(order);
                    list.Remove(existOrder);
                }
                else
                {
                    order.Id = obj.ID;
                    order.ProductName = obj.PartnerName;
                    order.Alias = obj.Alias;
                    order.Price = obj.CurrentPrice.Value;
                    order.Quantity = tempQuality;
                    order.SubTotal = tempQuality * obj.CurrentPrice.Value;
                    list.Add(order);
                }
                result.Data = AddToCookie(list);
            }
            else
            {
                result.Data = string.Empty;
            }
            return result;
        }

        private string AddToCookie(List<Order> list)
        {
            list = list.OrderBy(q => q.ProductName).ToList();
            string result = string.Empty;
            double total = 0;
            HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
            if (orderCookie == null)
            {
                orderCookie = new HttpCookie(Constants.ORDER_COOKIE);
            }

            orderCookie.Value = string.Empty;
            foreach (Order item in list)
            {
                orderCookie.Value += item.Id + "@" + item.ProductName + "@" + item.Quantity + "@" + item.Price + "@" + item.SubTotal + "@" + item.Alias + "#";
                result += item.Id + "@" + item.ProductName + "@" + item.Quantity + "@" + String.Format("{0:0,0}", item.Price) + "@"
                    + String.Format("{0:0,0}", item.SubTotal) + "#";
                total += item.SubTotal;
            }
            result = result.TrimEnd('#');
            result += "^" + String.Format("{0:0,0}", total);
            orderCookie.Value = orderCookie.Value.TrimEnd('#');
            orderCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(orderCookie);
            return result.TrimEnd('#');
        }

        public ActionResult Delete(string alias)
        {

            List<Order> list = GetOrderList();
            Order order = list.Where(c => c.Alias == alias).FirstOrDefault<Order>();
            if (order != null)
            {
                list.Remove(order);
                AddToCookie(list);
            }
            return RedirectToAction("Payment");
        }

        private List<Order> GetOrderList()
        {
            HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
            try
            {
                List<Order> list = new List<Order>();
                if (orderCookie != null)
                {
                    if (!string.IsNullOrEmpty(orderCookie.Value))
                    {
                        string[] products = orderCookie.Value.Split('#');
                        foreach (string product in products)
                        {
                            string[] prop = product.Split('@');
                            Order cookieOrder = new Order();
                            cookieOrder.Id = int.Parse(prop[0]);
                            cookieOrder.ProductName = prop[1];
                            cookieOrder.Quantity = int.Parse(prop[2]);

                            Partner partner = partDao.GetByID(cookieOrder.Id);
                            cookieOrder.Image = partner.Logo;
                            cookieOrder.Alias = partner.Alias;
                            cookieOrder.ProductName = partner.PartnerName;
                            cookieOrder.Price = partner.CurrentPrice.HasValue ? partner.CurrentPrice.Value : 0;
                            cookieOrder.SubTotal = (cookieOrder.Price * cookieOrder.Quantity);
                            list.Add(cookieOrder);
                        }
                    }
                }

                return list;
            }
            catch
            {
                orderCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(orderCookie);
                return new List<Order>();
            }
        }

        public void SetCaptcha()
        {

            //*** Editable Values
            int[] BackgroundColor = new int[] { 255, 255, 255 };// The 3 numbers represent in order RED, GREEN, BLUE for the captcha's background color
            bool RandomBackgroundNoiseColor = false;// True / False. If you choose True, BackgroundNoiseColor will not apply 
            bool RandomTextColor = false;// True / False. If you choose True, TextColor will not apply 
            int[] BackgroundNoiseColor = new int[] { 150, 150, 150 };// The 3 numbers represent in order RED, GREEN, BLUE
            int[] TextColor = new int[] { 100, 100, 100 };// The 3 numbers represent in order RED, GREEN, BLUE
            HatchStyle BackgroundNoiseTexture = HatchStyle.Divot;// replace ".Min" with any of the following: Horizontal, Vertical, ForwardDiagonal, BackwardDiagonal, Cross, DiagonalCross, Percent05, Percent10, Percent20, Percent25, Percent30, Percent40, Percent50, Percent60, Percent70, Percent75, Percent80, Percent90, LightDownwardDiagonal, LightUpwardDiagonal, DarkDownwardDiagonal, DarkUpwardDiagonal, WideDownwardDiagonal, WideUpwardDiagonal, LightVertical, LightHorizontal, NarrowVertical, NarrowHorizontal, DarkVertical, DarkHorizontal, DashedDownwardDiagonal, DashedUpwardDiagonal, DashedHorizontal, DashedVertical, SmallConfetti, LargeConfetti, ZigZag, Wave, DiagonalBrick, HorizontalBrick, Weave, Plaid, Divot, DottedGrid, DottedDiamond, Shingle, Trellis, Sphere, SmallGrid, SmallCheckerBoard, LargeCheckerBoard, OutlinedDiamond, SolidDiamond, LargeGrid, Min, Max
            int length = 6;// Number of characters to generate
            //*** END Editable Valuese

            int height = 60;
            int width = 300;
            width = width + ((length - 6) * 30);
            Random ranRotate = new Random();

            string strText = System.Guid.NewGuid().ToString();
            strText = strText.Replace("-", String.Empty);
            strText = strText.Substring(0, length);
            TempData["CaptchaValue"] = strText;

            Bitmap bmpCanvas = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            Graphics graCanvas = Graphics.FromImage(bmpCanvas);
            RectangleF recF = new RectangleF(0, 0, width, height);
            Brush bruBackground = default(Brush);
            SolidBrush letterBrush = default(SolidBrush);

            if (RandomBackgroundNoiseColor == true)
            {
                bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))), Color.FromArgb(BackgroundColor[0], BackgroundColor[1], BackgroundColor[2]));
            }
            else
            {
                bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb(238, 221, 130), Color.FromArgb(238, 222, 170));
            }

            graCanvas.FillRectangle(bruBackground, recF);

            if (RandomTextColor == true)
            {
                letterBrush = new SolidBrush(Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))));
            }
            else
            {
                letterBrush = new SolidBrush(Color.FromArgb(139, 69, 19));
            }

            System.Drawing.Drawing2D.Matrix matRotate = new System.Drawing.Drawing2D.Matrix();
            int i = 0;
            for (i = 0; i <= strText.Length - 1; i++)
            {
                matRotate.Reset();
                int intChars = strText.Length;
                int x = width / (intChars + 1) * i;
                int y = height / 2;
                //matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(width / (intChars + 1) * i, height * 0.5) );
                // matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(x, y));
                graCanvas.Transform = matRotate;
                if (i == 0)
                {
                    //draw ‘the text on our image
                    //graCanvas.DrawString(strText.Chars(i), new Font("Comic Sans MS", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, height * 0.4);
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Times New Roman", 30, FontStyle.Bold), letterBrush, 20, 10);
                }
                else if (i == 1)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Arial", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 2)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Times New Roman", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 3)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Georgia", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 4)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else if (i == 5)
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Geneva", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
                }
                else
                {
                    //draw ‘the text on our image
                    graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
                }
                graCanvas.ResetTransform();
            }
            //Response.ContentType = "image/GIF";
            bmpCanvas.Save(Response.OutputStream, ImageFormat.Gif);
            graCanvas.Dispose();
            bmpCanvas.Dispose();
        }

        #endregion

        #region Utilities
        public bool IsValidEmailAddress(string EmailAddress)
        {

            Regex regEmail = new Regex(@"^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (regEmail.IsMatch(EmailAddress))
                return true;

            return false;

        }
        public bool SendMail(string Host, String Port, string FromEmail, string FromName, string ToEmail, string ccEmail, string Subject, string Body)
        {
            MailMessage Msg = new MailMessage();
            Msg.From = new MailAddress(FromEmail, FromName);
            if (ToEmail.Contains(";"))
            {
                string[] toEmailAddress = ToEmail.Split(';');
                foreach (string address in toEmailAddress)
                {
                    if (!string.IsNullOrEmpty(address.Trim()))
                        if (IsValidEmailAddress(address.Trim()))
                            Msg.To.Add(new MailAddress(address.Trim()));
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(ToEmail.Trim()))
                    if (IsValidEmailAddress(ToEmail.Trim()))
                        Msg.To.Add(new MailAddress(ToEmail.Trim()));
            }

            if (ccEmail.Contains(";"))
            {
                string[] ccEmailAddress = ccEmail.Split(';');
                foreach (string address in ccEmailAddress)
                {
                    if (!string.IsNullOrEmpty(address.Trim()))
                        Msg.CC.Add(new MailAddress(address.Trim()));
                }
            }

            string bcc = ConfigurationManager.AppSettings["bcc"];
            if (!string.IsNullOrEmpty(bcc))
            {
                string[] bccArr = bcc.Split(';');
                foreach (string bccItem in bccArr)
                {
                    Msg.Bcc.Add(bccItem);
                }
            }

            Msg.IsBodyHtml = true;
            Msg.Subject = Subject;
            Msg.Body = Body;
            SmtpClient objMail = new SmtpClient(Host, Convert.ToInt32(Port));
            try
            {
                objMail.Send(Msg);
                return true;
            }
            catch (SmtpException ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}
